<template>
  <BasicModal
    v-bind="$attrs"
    :width="600"
    :minHeight="300"
    :maxHeight="400"
    :centered="true"
    :canFullscreen="false"
    :title="`${modalTitle}站点维护设置`"
    :cancelText="`${$t('common.cancelText')}`"
    :okText="`${$t('common.saveText')}`"
    @register="registerModal"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerVip" :label-width="labelWidth" class="editVipModal">
      <template #startTime="{ model, field }">
        <DatePicker
          format="YYYY-MM-DD HH:mm:ss"
          :show-time="{ defaultValue: dayjs('00:00:00', 'HH:mm:ss') }"
          v-model:value="model[field]"
          :disabledDate="disabledStartDate"
          @change="onStartDateChange"
          :showNow="false"
          :disabled-time="disabledDateStartTime"
        />
      </template>
      <template #endTime="{ model, field }">
        <DatePicker
          format="YYYY-MM-DD HH:mm:ss"
          :show-time="{ defaultValue: dayjs('00:00:00', 'HH:mm:ss') }"
          v-model:value="model[field]"
          :disabledDate="disabledEndDate"
          @change="onEndDateChange"
          :disabled-time="disabledDateEndTime"
        />
      </template>
      <template #notice="{ model, field }">
        <RadioGroup v-model:value="currentLangIndex" button-style="solid" :size="FORM_SIZE">
          <RadioButton
            class="!m-r-3 !m-b-3"
            v-for="(item, index) in contentList"
            :key="index"
            @click="handleClickContent(index, item)"
            :value="index"
            >{{ item.label }}</RadioButton
          >
        </RadioGroup>
        <FormItem>
          <Textarea
            style="margin-top: 8px"
            :placeholder="'维护说明'"
            status="error"
            :value="textValue"
            v-model:value="model[field]"
            @change="handelTextValueChange"
          />
        </FormItem>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, watch, nextTick } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { editData } from './safeGuard.data';
  import dayjs, { Dayjs } from 'dayjs';
  import moment from 'moment';
  import {
    Tabs,
    TabPane,
    DatePicker,
    Textarea,
    Button,
    message,
    FormItem,
    RadioGroup,
    RadioButton,
  } from 'ant-design-vue';
  import { BasicForm, useForm } from '@/components/Form';
  import EditTable from './EditTable.vue';
  //import LangRadioGroup from './LangGroup.vue';
  import { useI18n } from '@/hooks/web/useI18n';
  import { setDateParmas, timeChange, formatToDateTime } from '@/utils/dateUtil';
  import { configMaintain } from '@/api/sys';
  import { useFormSetting } from '@/hooks/setting/useFormSetting';
  import { LangItem } from '@/views/system/informationCenter/common/setting';
  import { useLocalList } from '@/settings/localeSetting';
  import translateContentList from '@/views/system/informationCenter/common/language';

  const localeList = useLocalList();
  const modalTitle = ref('');
  const { t } = useI18n();
  const FORM_SIZE = useFormSetting().getFormSize;
  let extraList = [
    {
      label: '翻译原文',
      value: 'zh-CN',
      transitionValue: '',
      transitionValueBtn: '',
      btnShow: true,
      image_url: '',
      language: 'zh-CN',
    },
  ];
  const langList = localeList.map((item) => {
    return {
      label: item.text,
      value: item.event,
      transitionValue: '',
      transitionValueBtn: '',
      btnShow: true,
      image_url: '',
      language: item.language || '',
      fileList: [],
    };
  });
  interface FormModel {
    maintain_start_time: Date | null;
    maintain_end_time: Date | null;
  }
  const selectIndex = ref(0);
  const langRef = ref(null as any);
  const setStatus = ref('error' as any);
  const statusText = ref('');
  const isIndex = ref(0 as Number);
  const contentList = ref<Array<LangItem>>([...extraList, ...langList]);
  const currentLang = ref(contentList.value[0]);
  const textValue = ref('');
  const helpMessage = ref('');
  const startTime = ref<Dayjs>();
  const model = ref<FormModel>({
    maintain_start_time: dayjs().startOf('day').toDate(),
    maintain_end_time: dayjs().endOf('day').toDate(),
  });
  export default defineComponent({
    name: 'SafeGuardModal',
    components: {
      BasicModal,
      EditTable,
      Tabs,
      TabPane,
      BasicForm,
      DatePicker,
      Textarea,
      Button,
      // LangRadioGroup,
      FormItem,
      RadioGroup,
      RadioButton,
    },
    props: ['labelWidth'],
    emits: ['register', 'submit', 'success'],
    setup(_, { emit, props }) {
      let closeReload = function () {};
      const baseTableConfig = {
        showIndexColumn: false,
        pagination: false,
        actionColumn: {
          width: 120,
          title: t('business.common_operate'), //操作
          dataIndex: 'action',
        },
      };

      const labelWidth = ref();
      const checkboxValue = ref();
      const currentLangIndex = ref(0 as any);
      const tinymceIsChange = ref(false);
      const dataFormat = 'YYYY-MM-DD HH:mm:ss';
      //const startTime = ref<Dayjs>(dayjs('2015/01/01 23:33', dataFormat.value))
      // var nowDate = dayjs(new Date()).format('YYYY/MM/DD HH:mm');
      // var startTime = ref<Dayjs>(dayjs('2015/01/01 23:33', dataFormat));
      // var endTime = ref<Dayjs>();
      const [
        registerVip,
        { resetFields, clearValidate, validate, setFieldsValue, getFieldsValue },
      ] = useForm({
        schemas: editData,
        showActionButtonGroup: false,
        //labelWidth: '150px',
        size: FORM_SIZE,
      });
      let title = ref('');
      let dataId = ref('');
      // let apiParms = ref();
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        closeReload = data.reloadData;
        modalTitle.value = data.record.name;
        isIndex.value = 0;
        nextTick(() => {
          console.log(langRef.value);
        });
        setTimeout(() => {
          handleClickContent(0);
        }, 500);
        currentLang.value = contentList.value[0];
        let initStart = data.record.maintain_start_time * 1000;
        let initEnd = data.record.maintain_end_time * 1000;
        let initData = getFieldsValue();
        initData.maintain = data.record.maintain;
        if (initData.maintain === 1) {
          initData.maintain_start_time = dayjs();
          initData.maintain_end_time = '';
          setFieldsValue({ maintain_end_time: '' });
        } else {
          initData.maintain_start_time = initStart;
          initData.maintain_end_time = initEnd;
        }
        dataId.value = data.record.id;
        setFieldsValue(initData);

        if (data.record.maintain_content) {
          if (initData.maintain === 2) {
            textValue.value = JSON.parse(data.record.maintain_content)
              ['zh-CN'].split('<p>')[1]
              .split('</p>')[0];
            contentList.value[0].transitionValue = textValue.value;
            translateContentList(
              contentList.value,
              JSON.parse(data.record.maintain_content)['zh-CN'].split('<p>')[1].split('</p>')[0],
              currentLangIndex.value,
            );
          } else {
            textValue.value = '';
          }
        }
        // apiParms.value = params;
        setModalProps({ confirmLoading: false });
      });
      const disabledStartDate = (date) => {
        if (!model.value.maintain_end_time || !date) return false;
        return date.valueOf() > model.value.maintain_end_time.valueOf();
      };
      const disabledEndDate = (date) => {
        if (!model.value.maintain_start_time || !date) return false;
        return date.valueOf() < model.value.maintain_start_time.valueOf();
      };
      const onStartDateChange = (value) => {
        model.value.maintain_start_time = value;
      };
      const onEndDateChange = (value) => {
        model.value.maintain_end_time = value;
      };
      const range = (start, end) => {
        const result = [];
        for (let i = start; i < end; i++) {
          result.push(i);
        }
        return result;
      };

      // 禁止选择当时之后的时刻
      const disabledDateStartTime = (date) => {
        const hours = moment().hours();
        const minutes = moment().minutes();
        const seconds = moment().seconds();
        return {
          disabledHours: () => range(hours + 1, 24),
          disabledMinutes: () => range(minutes + 1, 60),
          disabledSeconds: () => [],
        };
      };
      //禁止选择以后的时间
      const disabledDateEndTime = (date) => {
        const hours = moment().hours();
        const minutes = moment().minutes();
        const seconds = moment().seconds();
        return {
          disabledHours: () => range(0, hours),
          disabledMinutes: () => range(0, minutes + 1),
          disabledSeconds: () => [],
        };
      };

      const handleClickContent = (idx) => {
        currentLangIndex.value = idx;
        tinymceIsChange.value = false;
        currentLang.value = contentList.value[idx];
        textValue.value = contentList.value[idx].transitionValue;
      };

      const handelTextValueChange = (e) => {
        textValue.value = e.target.value;
        if (currentLangIndex.value === 0) {
          translateContentList(contentList.value, e.target.value, currentLangIndex.value);
        }
        contentList.value[currentLangIndex.value].transitionValue = textValue.value;
      };
      async function handleSubmit(e): Promise<void> {
        try {
          setModalProps({ confirmLoading: true });
          const { maintain, maintain_start_time, maintain_end_time } = getFieldsValue();
          let maintain_content = {};
          for (let i = 0; i < contentList.value.length; i++) {
            maintain_content[contentList.value[i].value] =
              '<p>' + contentList.value[i].transitionValue + '</p>';
          }
          // if (!maintain_end_time) {
          //   return message.error('请选择结束时间')
          // }
          let _data = {
            id: String(dataId.value),
            maintain,
            maintain_start_time: timeChange(formatToDateTime(maintain_start_time)) / 1000,
            maintain_end_time: timeChange(formatToDateTime(maintain_end_time)) / 1000,
            maintain_content,
          };
          if (maintain === 2 && !textValue.value) {
            setStatus.value = 'error';
            helpMessage.value = '请输入维护说明';
            return message.error('请输入维护说明');
          }
          const { status, data } = await configMaintain(_data);
          if (status) {
            emit('success');
            closeReload && closeReload();
            closeModal();
            selectIndex.value = 0;
            message.success(data);
          } else {
            message.error(data);
          }
        } catch (e) {
          console.log(e);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return {
        // columns,
        modalTitle,
        registerModal,
        handleSubmit,
        title,
        registerVip,
        labelWidth,
        dayjs,
        //LangRadioGroup,
        contentList,
        handleClickContent,
        currentLang,
        textValue,
        handelTextValueChange,
        translateContentList,
        disabledStartDate,
        disabledEndDate,
        onStartDateChange,
        onEndDateChange,
        currentLangIndex,
        disabledDateStartTime,
        disabledDateEndTime,
      };
    },
  });
</script>
<style lang="less" scoped>
  .languageBox {
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: auto;
    //padding-left: 20px;
    //padding-right: 20px;
    //background-color: rgb(70, 76, 91);
  }

  .bannerLanguage {
    display: inline-block;
    width: 68px;
    height: 33px;
    margin-top: 4px;
    margin-right: 4px;
    border: 1px solid rgb(2 167 240 / 100%);
    color: rgb(2 167 240 / 100%);
    line-height: 33px;
    text-align: center;
    cursor: pointer;
  }

  .bannerLanguageChecked {
    background: linear-gradient(90deg, rgb(27 194 216 / 100%) 0%, rgb(64 158 255 / 100%) 100%);
    color: #fff;
  }
</style>
